<template>
  <a-modal
    title="编辑博客信息"
    width="62%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-tabs default-active-key="1">
      <a-tab-pane key="1">
        <span slot="tab">
          <a-icon type="form"/>
          博客信息
        </span>
        <a-spin :spinning="confirmLoading">
          <a-form :form="form">
            <a-form-item v-show="false">
              <a-input v-decorator="['blogId']"/>
            </a-form-item>
            <a-form-item
              label="博客标题"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                placeholder="请输入博客标题"
                v-decorator="['blogTitle', {rules: [{required: true, message: '请输入博客标题！'}]}]"/>
            </a-form-item>
            <a-form-item
              label="博客自定义路径url"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                placeholder="请输入博客自定义路径url"
                v-decorator="['blogSubUrl', {rules: [{required: false, message: '请输入博客自定义路径url！'}]}]"/>
            </a-form-item>
            <a-form-item
              label="博客前言"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                placeholder="请输入博客前言"
                v-decorator="['blogPreface', {rules: [{required: true, message: '请输入博客前言！'}]}]"/>
            </a-form-item>
            <a-form-item
              label="banner"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                placeholder="请输入博客banner"
                v-decorator="['banner', {rules: [{required: true, message: '请输入博客banner！'}]}]"/>
            </a-form-item>

            <a-form-item
              label="博客分类"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-select
                name="blogCategoryId"
                size="default"
                @change="syncName"
                v-decorator="['blogCategoryId', {rules: [{required: true, message: '请选择博客分类！'}]}]">
                <a-select-option v-for="item in blogCategory" :key="item.categoryId">
                  {{ item.categoryName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              v-show="false"
              label="博客分类"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                name="blogCategoryName"
                :value="blogCategoryName"
                placeholder="请输入博客分类"
                rules="blogCategoryName:[{required: true, message: '请输入博客分类！'}]"/>
            </a-form-item>
            <a-form-item
              label="博客标签"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                placeholder="请输入博客标签"
                :disabled="true"
                v-decorator="['blogTags', {rules: [{required: true, message: '请输入博客标签！'}]}]"/>

              <a-transfer
                :titles="['所有标签', '博客标签']"
                :list-style="{width: '250px',height: '300px'}"
                :data-source="tagData"
                show-search
                :filter-option="filterOption"
                :target-keys="targetKeys"
                :render="item => item.title"
                @change="handleChange"
                @search="handleSearch"
              />
            </a-form-item>
            <a-form-item
              label="博客状态"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-radio-group
                placeholder="请选择博客状态"
                v-decorator="['blogStatus',{rules: [{ required: true, message: '请选择博客状态！' }]}]">
                <a-radio v-for="(item,index) in blogStatusData" :key="index" :value="parseInt(item.code)">{{
                    item.name
                  }}
                </a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item
              label="评论状态"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-radio-group
                placeholder="请选择是否允许评论"
                v-decorator="['enableComment',{rules: [{ required: true, message: '请选择是否允许评论！' }]}]">
                <a-radio v-for="(item,index) in enableCommentData" :key="index" :value="parseInt(item.code)">{{
                    item.name
                  }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              label="是否删除"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-radio-group
                placeholder="请选择是否删除"
                v-decorator="['isDeleted',{rules: [{ required: true, message: '请选择是否删除！' }]}]">
                <a-radio v-for="(item,index) in isDeletedData" :key="index" :value="parseInt(item.code)">{{
                    item.name
                  }}
                </a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item
              label="阅读量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input-number
                disabled
                placeholder="自动生成"

                v-decorator="['blogViews', {rules: [{required: true, message: '请输入阅读量！'}]}]"/>

            </a-form-item>
            <a-form-item
              label="点赞数"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input-number
                disabled
                placeholder="自动生成"

                v-decorator="['likeNum', {rules: [{required: false, message: '请输入点赞数！'}]}]"/>
            </a-form-item>
          </a-form>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane key="2">
        <span slot="tab">
          <a-icon type="highlight"/>
          博客内容
        </span>
        <p>
          <a-tag color="blue">
            编辑:
          </a-tag>
        </p>
        <mavon-editor
          :defaultOpen="'edit'"
          :value="this.blogContent"
          @change="mdChange"
          @imgAdd="imgAdd"
          ref="md"
          :externalLink="externalLink"/>
        <p></p>
        <p>
          <a-tag color="cyan">
            预览:
          </a-tag>
        </p>
        <mavon-editor
          class="md"
          :value="this.blogContent"
          :subfield="false"
          :defaultOpen="'preview'"
          :toolbarsFlag="false"
          :editable="false"
          :scrollStyle="true"
          :ishljs="true"
          :externalLink="externalLink"
        ></mavon-editor>

      </a-tab-pane>
      <a-tab-pane key="3">
        <span slot="tab">
          <a-icon type="message"/>
          评论
        </span>
        <a-spin tip="加载中..." :spinning="spinning" size="large">
          <a-empty :image="simpleImage" v-if="total===0"/>
          <div v-for="content in contents" :key="content">
            <blogComment
              :content="content"
              @parentFun="onCommentPageChange"
            ></blogComment>
          </div>

          <template>
            <a-pagination
              style="display: inline-flex;padding-right: 1%"
              size="small"
              :total="total"
              show-size-changer
              show-quick-jumper
              :defaultPage="pageNo"
              :defaultPageSize="pageSize"
              :pageSizeOptions="['5', '10', '20', '40']"
              :show-total="total => `共 ${total} 条`"
              @change="onCommentPageChange"
              @showSizeChange="onCommentPageChange"/>
            <a-button
              type="default"
              shape="circle"
              icon="reload"
              size="small"
              :loading="iconLoading"
              @click="onCommentPageChange(pageNo,pageSize)"></a-button>
          </template>
        </a-spin>
      </a-tab-pane>
    </a-tabs>

  </a-modal>
</template>

<script>

import Vue from 'vue'
import 'mavon-editor/dist/css/index.css'
import mavonEditor from 'mavon-editor'
import {blogInfoEdit} from '@/api/modular/main/bloginfo/blogInfoManage'
import {blogCategoryList} from '@/api/modular/main/blogcategory/blogCategoryManage'
import {blogTagList} from '@/api/modular/main/blogtag/blogTagManage'
import {getFileUrl, getUploadToken} from '@/api/modular/main/qiniu/qiniu'
// import { blogTagRelationEdit } from '@/api/modular/main/blogtagrelation/blogTagRelationManage'
import blogComment from '@/views/main/bloginfo/blogComment'
import {blogCommentPage} from '@/api/modular/main/blogcomment/blogCommentManage'
import {getTimer} from '@/utils/util'

const qiniu = require('qiniu-js')

Vue.use(mavonEditor)

export default {
  components: {
    blogComment
  },
  data() {
    return {

      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15}
      },
      enableCommentData: [],
      blogStatusData: [],
      isDeletedData: [],
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      blogContent: '',
      blogCategory: [],
      blogCategoryName: '未找到目录名',
      tagData: [],
      targetKeys: [],
      contents: [],
      total: 0,
      iconLoading: false,
      pageSize: 5,
      pageNo: 1,
      spinning: false,
      externalLink: {
        markdown_css: function () {
          // 这是你的markdown css文件路径
          return '/cdn-lib/markdownCss/github-markdown.min.css'
        },
        hljs_js: function () {
          // 这是你的hljs文件路径
          return '/cdn-lib/highlight/highlight.min.js'
        },
        katex_css: function () {
          // 这是你的katex配色方案路径路径
          return '/cdn-lib/KaTex/katex.min.css'
        },
        katex_js: function () {
          // 这是你的katex.js路径
          return '/cdn-lib/KaTex/katex.min.js'
        }
      }
    }
  },
  methods: {
    // 初始化方法
    edit(record) {
      this.visible = true

      const options = this.$options
      this.blogStatusData = options.filters['dictData']('dict_blog_status')
      this.enableCommentData = options.filters['dictData']('dict_enable_comment')
      this.isDeletedData = options.filters['dictData']('dict_is_deleted')

      blogCategoryList().then((res) => {
        this.blogCategory = res.data
      })

      blogCommentPage({pageNo: 1, pageSize: 5, blogId: record.blogId, isParent: true}).then((res) => {
        for (let i = 0; i < res.data.rows.length; i++) {
          res.data.rows[i].createTime_fast = getTimer(res.data.rows[i].createTime)
        }
        this.contents = res.data.rows
        this.total = res.data.totalRows
      })

      setTimeout(() => {
        this.blogContent = record.blogContent
        this.blogCategoryName = record.blogCategoryName
        this.form.setFieldsValue(
          {
            blogId: record.blogId,
            blogTitle: record.blogTitle,
            blogSubUrl: record.blogSubUrl,
            banner: record.banner,
            blogPreface: record.blogPreface,
            blogContent: record.blogContent,
            blogCategoryId: record.blogCategoryId,
            blogCategoryName: record.blogCategoryName,
            blogTags: record.blogTags,
            blogStatus: record.blogStatus,
            blogViews: record.blogViews,
            enableComment: record.enableComment,
            isDeleted: record.isDeleted,
            likeNum: record.likeNum
          }
        )
        this.getMock()
      }, 100)
    },
    handleSubmit() {
      const {form: {validateFields}} = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            if (values[key] && (typeof (values[key]) === 'object')) {
              values[key] = JSON.stringify(values[key])
            }
          }
          values.blogContent = this.blogContent
          values.blogCategoryName = this.blogCategoryName

          blogInfoEdit(values).then((res) => {
            if (res.success) {
              this.$message.success('编辑成功')
              this.confirmLoading = false
              this.$emit('ok', values)
              this.handleCancel()

              const param = []
              for (let i = 0; i < this.tagData.length; i++) {
                for (let j = 0; j < this.targetKeys.length; j++) {
                  if (this.tagData[i].key === this.targetKeys[j]) {
                    this.tagData[i].blogId = values.blogId
                    this.tagData[i].tagId = this.tagData[i].key
                    param.push(this.tagData[i])
                  }
                }
              }
              /* blogTagRelationEdit(param).then((res) => {

              }) */
            } else {
              this.$message.error('编辑失败' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    },
    mdChange(e) {
      this.blogContent = e
    },
    syncName(e) {
      for (let i = 0; i < this.blogCategory.length; i++) {
        if (this.blogCategory[i].categoryId === e) {
          this.blogCategoryName = this.blogCategory[i].categoryName
        }
      }
    },
    getMock() {
      const targetKeys = []
      const tagData = []
      const arr = this.form.getFieldValue('blogTags').split(',')
      blogTagList().then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          const data = {
            key: res.data[i].tagId,
            title: res.data[i].tagName,
            description: res.data[i].tagName,
            chosen: false
          }
          for (let j = 0; j < arr.length; j++) {
            if (res.data[i].tagName === arr[j]) {
              data.chosen = true
              targetKeys.push(data.key)
            }
          }
          tagData.push(data)
        }
      })
      this.tagData = tagData
      this.targetKeys = targetKeys
    },
    filterOption(inputValue, option) {
      return option.description.indexOf(inputValue) > -1
    },
    handleChange(targetKeys, direction, moveKeys) {
      const tagData = this.tagData
      this.form.setFieldsValue({
        'blogTags': ''
      })
      for (let i = 0; i < targetKeys.length; i++) {
        for (let j = 0; j < tagData.length; j++) {
          if (tagData[j].key === targetKeys[i]) {
            let pre = this.form.getFieldValue('blogTags')
            if (pre) {
              pre = pre + ','
            }
            this.form.setFieldsValue({
              'blogTags': pre + tagData[j].title
            })
          }
        }
      }
      this.targetKeys = targetKeys
    },
    handleSearch(dir, value) {
      console.log('search:', dir, value)
    },
    onCommentPageChange(page, pageSize) {
      if (pageSize !== undefined) {
        this.pageSize = pageSize
      }
      if (page !== undefined) {
        this.pageNo = page
      }
      this.iconLoading = true
      this.spinning = true
      blogCommentPage({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        blogId: this.form.getFieldValue('blogId'),
        isParent: true
      }).then((res) => {
        for (let i = 0; i < res.data.rows.length; i++) {
          res.data.rows[i].createTime_fast = getTimer(res.data.rows[i].createTime)
        }
        this.contents = res.data.rows
        this.total = res.data.totalRows
        this.iconLoading = false

        this.spinning = false
      })
    },
    imgAdd(pos, $file) {
      let that = this
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      }
      const options = {
        quality: 0.92,
        noCompressIfLarger: true
        // maxWidth: 1000,
        // maxHeight: 618
      }
      const putExtra = {
        fname: $file.filename,
        mimeType: $file.type
      }

      getUploadToken({}).then((res) => {
        qiniu.compressImage($file, options).then(data => {
          const token = res.data
          const observable = qiniu.upload($file, null, token, putExtra, config)
          const subscription = observable.subscribe({
            next(res) {

            },
            error(err) {
              that.$message.error('上传错误! info：' + JSON.stringify(err))
            },
            complete(res) {
              that.$message.success('上传完成!')
              that.$refs.md.$img2Url(pos, process.env.VUE_APP_QINIU_URL + "/" + res.key)
            }
          }) // 上传开始
        })
      })


      // 第一步.将图片上传到服务器.
      /*      var formdata = new FormData()
            formdata.append('file', $file)
            sysFileInfoUpload(formdata).then((res) => {
              if (res.success) {
                this.$message.success('上传成功！')
                this.$refs.md.$img2Url(pos, process.env.VUE_APP_FRONT_URL + '/api/sysFileInfo/preview?id=' + res.data)
              } else {
                this.$message.error(res.message)
              }
            }) */
    }

  }
}
</script>
<style>
.spin-content {
  border: 1px solid #91d5ff;
  background-color: #e6f7ff;
  padding: 30px;
}

p {
  cursor: default;
}

.ant-comment-inner {
  padding: 5px 0;
}

.ant-modal-body {
  padding-top: 0;
  padding-bottom: 1%;
}

.ant-divider-horizontal {
  margin: 2% 0 0 0;
}

.ant-transfer-list {
  height: 260px !important;
}
</style>
